
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace SoftwareMonkeys.Scriptech.Configuration
{
	[XmlRoot("Properties")]
	[XmlType("Properties")]
	public class PropertiesCollection : Dictionary<string, string>, IXmlSerializable
	{
		public new string this[string key] {
			get {
				if (this.ContainsKey (key))
					return base[key];
				else
					return string.Empty;
			}
			set { base[key] = value; }
		}

		#region IXmlSerializable Members

		public System.Xml.Schema.XmlSchema GetSchema ()
		{
			
			return null;
			
		}



		public void ReadXml (System.Xml.XmlReader reader)
		{
			
			XmlSerializer keySerializer = new XmlSerializer (typeof(string));
			
			XmlSerializer valueSerializer = new XmlSerializer (typeof(string));
			
			
			
			bool wasEmpty = reader.IsEmptyElement;
			
			reader.ReadStartElement("Properties");
			
			
			
			if (wasEmpty)
				
				return;
			
			while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
			{
					//reader.ReadStartElement ("Property");
					
					string key = reader.GetAttribute ("Name");
					
					string value = reader.GetAttribute ("Value");
					//reader.ReadEndElement ();
					
					
					this.Add(key, value);
				
				reader.ReadToNextSibling("Property");
			}
			
			//reader.ReadEndElement ();
			
		}



		public void WriteXml (System.Xml.XmlWriter writer)
		{
			foreach (string key in this.Keys) {
				writer.WriteStartElement ("Property");
				
				writer.WriteAttributeString ("Name", key);
				
				writer.WriteAttributeString ("Value", this[key]);
				
				writer.WriteEndElement ();
			}
		}

		#endregion

		public static PropertiesCollection Load (string filePath)
		{
			PropertiesCollection properties = new PropertiesCollection ();
			
			using (StreamReader reader = new StreamReader (File.OpenRead (filePath))) {
				XmlSerializer serializer = new XmlSerializer (typeof(PropertiesCollection));
				properties = (PropertiesCollection)serializer.Deserialize (reader);
			}
			
			return properties;
		}

		public void Save (string filePath)
		{
			using (StreamWriter writer = File.CreateText (filePath)) {
				XmlSerializer serializer = new XmlSerializer (GetType ());
				serializer.Serialize (writer, this);
				
			}
		}
	}
	
}
